//
//  OrgEmpViewController.m
//  代办事宜
//
//  Created by wang on 12-8-27.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "OrgEmpViewController.h"
#import "DealWithBackLogViewController.h"
#import "UIViewPassValueDelegate.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"



@interface OrgEmpViewController ()<UITableViewDelegate,UITableViewDataSource,UIPickerViewDataSource,UIPickerViewDelegate,ASIHTTPRequestDelegate>
@property (strong,nonatomic)  UITableView*mytableView;
@property (nonatomic, retain) NSArray *arrayOriginal;
@property (nonatomic, retain) NSMutableArray *arForTable;
@property (nonatomic, strong) UIPickerView *empPick;
@property (nonatomic, strong) NSDictionary* empInfo;


@end

@implementation OrgEmpViewController
@synthesize arrayOriginal=_arrayOriginal;
@synthesize arForTable=_arForTable;
@synthesize mytableView=_mytableView;
@synthesize delegate=_delegate;
@synthesize empPick=_empPick;
@synthesize empInfo=_empInfo;

NSMutableDictionary* cellFlagDictory;
NSArray* orgEmpArray;



- (void)viewDidLoad
{
	[super viewDidLoad];
    self.title=@"组织架构";
    self.view.contentMode = UIViewContentModeScaleAspectFill;
    //组织
    self.mytableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 
                                                                     755)
                                                    style:UITableViewStylePlain];    
    [self.mytableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [self.mytableView setDelegate:self];
    [self.mytableView setDataSource:self];
    [self.mytableView setEditing:NO animated:NO];
    [self.mytableView setBackgroundColor:[UIColor cyanColor]];
    [self.view addSubview: self.mytableView];
        
    //toobar
    UIToolbar*toolbar=[[UIToolbar alloc] initWithFrame:CGRectMake(0, 755, 100, 40)];
    [toolbar sizeToFit];
    toolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth;//这句作用是切换时宽度自适应.
    UIBarButtonItem* barItem1 = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonSystemItemAction  target:self action:@selector(saveOrgEmp:)];
     UIBarButtonItem* barItem2 = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonSystemItemAction  target:self action:@selector(cannelSaveOrgEmp:)];
    NSMutableArray*items=[[NSMutableArray alloc] initWithCapacity:3];
    [items addObject:barItem1];
    [items addObject:barItem2];
    [toolbar setItems:items animated:YES];
    [self.view addSubview:toolbar]; 
    
    //人员
    self.empPick=[[UIPickerView alloc] initWithFrame:CGRectZero];
    self.empPick.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    self.empPick.dataSource = self;
    self.empPick.delegate = self; 
    self.empPick.frame = CGRectMake(0, 798, self.view.bounds.size.width, 
                                       100);        
    self.empPick.showsSelectionIndicator = YES; 
    [self.view addSubview:self.empPick];    
	NSDictionary *dTmp=[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]];
	self.arrayOriginal=[dTmp valueForKey:@"Objects"];	
	self.arForTable=[[NSMutableArray alloc] init];
	[self.arForTable addObjectsFromArray:self.arrayOriginal];
    cellFlagDictory=[[NSMutableDictionary alloc]init];
	
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
 


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return [self.arForTable count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
	cell.textLabel.text=[NSString stringWithFormat:@"%@-[%@]",[[self.arForTable objectAtIndex:indexPath.row] valueForKey:@"orgLevel"],[[self.arForTable objectAtIndex:indexPath.row] valueForKey:@"orgName"]];
	[cell setIndentationLevel:[[[self.arForTable objectAtIndex:indexPath.row] valueForKey:@"orgLevel"] intValue]*2];
    [cell setContentMode:UIViewContentModeScaleToFill];	

    

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(![cellFlagDictory objectForKey:indexPath]) 
    {
        [cellFlagDictory setObject:[[NSNumber alloc] initWithInt:1] forKey:indexPath];
    }else {
        NSNumber *tempNum= [cellFlagDictory objectForKey:indexPath] ;
        int i=[tempNum intValue]+1; 
        [cellFlagDictory setObject:[[NSNumber alloc] initWithInt:i] forKey:indexPath];
    }
    
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	
	NSDictionary *d=[self.arForTable objectAtIndex:indexPath.row];
	if(d) {
        //同步取下级组织
        [self showMbprogress];
        NSString* u=[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"];
        NSURL *url = [NSURL URLWithString:u];    
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];    
        [request addPostValue: @"getOrgTreeListByPorgId" forKey:@"method"];
        [request addPostValue: [d objectForKey:@"orgId"] forKey:@"orgId"];
        [request startSynchronous];
        
        NSError *error = [request error];
        NSArray *ar;
        if (!error) {
            NSString *result = [request responseString];
            //ar=[d valueForKey:@"Objects"];
            ar= [result objectFromJSONString];
        }
		
		BOOL isAlreadyInserted=NO;  
        
        if([[cellFlagDictory objectForKey:indexPath] intValue] %2 == 0){
            NSLog(@"关闭");
           isAlreadyInserted=YES;
        }else {
            NSLog(@"打开");
        }
		
        NSUInteger count=indexPath.row+1;
		if(isAlreadyInserted) {
			[self miniMizeThisRows:ar withIndex:count];
		} else {		
			NSMutableArray *arCells=[NSMutableArray array];
			for(NSDictionary *dInner in ar ) {
				[arCells addObject:[NSIndexPath indexPathForRow:count inSection:0]];
				[self.arForTable insertObject:dInner atIndex:count++];
			}
			[tableView insertRowsAtIndexPaths:arCells withRowAnimation:UITableViewRowAnimationLeft];
		}
        if(!isAlreadyInserted){
        //同步取人员
        NSString* u2=[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"];
        NSURL *url2 = [NSURL URLWithString:u2];    
        ASIFormDataRequest *request2 = [ASIFormDataRequest requestWithURL:url2];    
        [request2 addPostValue: @"getAllUsersByOrgId" forKey:@"method"];
        [request2 addPostValue: [d objectForKey:@"orgId"] forKey:@"orgId"];
        [request2 startSynchronous];
        NSError *error2 = [request2 error];
        if (!error2) {
            NSString *result = [request2 responseString];
            orgEmpArray= [result objectFromJSONString];
        }
        [self.empPick reloadAllComponents];
        }
        [self hideMbProgress];
	}
}

-(void)miniMizeThisRows:(NSArray*)ar withIndex:(NSUInteger)count{
	
	for(NSDictionary *dInner in ar ) 
    {
                
        NSString*pId=[dInner valueForKey:@"orgId"];
    
        NSMutableArray *arInner=[[NSMutableArray alloc] init];
        NSUInteger i=0;        
        for(NSDictionary*obj in self.arForTable){
            if([[obj valueForKey:@"orgParentId"] isEqualToString:pId])
                [arInner insertObject:obj atIndex:i++];
        }
        
		if(arInner && [arInner count]>0){
                NSUInteger innerCount=[self.arForTable indexOfObject:dInner];
                [self miniMizeThisRows:arInner withIndex:innerCount];
		}
        
        if([self.arForTable indexOfObject:dInner]!=NSNotFound) 
        {
        [self.arForTable removeObject:dInner];
        [self.mytableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:
                                                  [NSIndexPath indexPathForRow:count inSection:0]]
                                                   withRowAnimation:UITableViewRowAnimationRight];
        }
    }
}

//人员
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [orgEmpArray count];   
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{

    NSDictionary*temp=[orgEmpArray objectAtIndex:row];
    return [[NSString alloc] initWithFormat:@"%@",[temp objectForKey:@"userName"]];
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    NSDictionary*temp=[orgEmpArray objectAtIndex:row];
    NSString* idAndName= [[NSString alloc] initWithFormat:@"%@",[temp objectForKey:@"userName"]];
    self.empInfo=temp;
    NSLog(@"%@ is selected.",idAndName);
    
}

-(void)saveOrgEmp:(id)sender{    
    [self.delegate passOrgEmpValue:self.empInfo];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)cannelSaveOrgEmp:(id)sender{    
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}


@end
